<template>
  <div class="type">
    <van-search
      @input="onSearch"
      class="fixed search"
      v-model="keyword"
      placeholder="请输入搜索关键词"
    />

    <van-tree-select :items="items" :main-active-index.sync="activeIndex">
      <template slot="content">
        <ul class="flex jc-sa fww">
          <li class="item" v-for="item in productList" :key="item.productId">
            <img :src="item.imgUrl" alt="" />
            <p class="f12">{{ item.masterName }}  </p>
          </li>
        </ul>
      </template>
    </van-tree-select>
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "@/components/Footer";
import $http from "@/utils/http";
export default {
  components: {
    Footer,
  },

  data() {
    return {
      // 搜索关键字
      keyword: "",
      activeIndex: -1,
      // 分类列表
      items: [],
      // 商品列表
      productList: [
        // {
        //   categoryId: "",
        //   categoryName: "",
        //   imgUrl: "",
        //   inventory: "",
        //   masterName: "",
        //   maxPrice: "",
        //   minPrice: "",
        //   productId: "",
        //   slaveName: "",
        // },
      ],
    };
  },

  created() {
    this.getTypeList();
  },

  watch: {
    activeIndex(newIndex) {
      let categoryId = this.items[newIndex].categoryId;
      this.getProductList(categoryId);
    },
  },

  methods: {
    onsearch() {
      if (!this.keyword) {
        let categoryId = this.items[this.activeIndex].categoryId;
        this.getProductList(categoryId);
      } else {
        let params = {
          keyword: this.keyword,
        };
        $http.get("/product/search", { params }).then((res) => {
          this.productList = res.list;
        });
        this.activeIndex = -1;
      }
    },

    // 获取分类列表并渲染
    getTypeList() {
      $http.get("/category/all").then((res) => { 
        // 获取首页传过来的index
        let index = this.$route.query.index;
        // 修改activeIndex的值, 触发watch从而去渲染商品列表 
        this.activeIndex = index || 0;
        this.items = res.list.map((item) => {
          return {
            ...item,
            text: item.name,
          };
        });
      });
    },

    // 根据分类编号categoryId获取商品列表
    getProductList(categoryId) {
      let params = {
        categoryId: categoryId,
      };
      $http.get("/product/list", { params }).then((res) => {
        this.productList = res.list;
      });
    },
  },
};
</script>

<style lang="less">
@import "./index.less";
</style> 

